package zabbix

import (
	"encoding/json"
	"errors"
)

func DruleCreateData() (string,map[string]interface{}) {
	method := "drule.create"
	var data map[string]interface{}
	jsonstr := []byte(`{
        "name": "Zabbix agent discovery",
        "iprange": "192.168.1.1-255",
        "dchecks": [
            {
                "type": "9",
                "key_": "system.uname",
                "ports": "10050",
                "uniq": "0"
            }
        ]	
	}`)
	json.Unmarshal(jsonstr,&data)
	return method,data
}

func DruleDeleteData() (string,map[string]interface{}) {
	method := "drule.delete"
	var data map[string]interface{}
	jsonstr := []byte(`[
        "4",
        "6"
	]`)
	json.Unmarshal(jsonstr,&data)
	return method,data
}

func DruleGetData() (string,map[string]interface{}) {
	method := "drule.get"
	var data map[string]interface{}
	jsonstr := []byte(`{
        "output": "extend",
        "selectDChecks": "extend"
	}`)
	json.Unmarshal(jsonstr,&data)
	return method,data
}

func DruleUpdateData() (string,map[string]interface{}) {
	method := "discovery.update"
	var data map[string]interface{}
	jsonstr := []byte(`{
        "druleid": "6",
        "iprange": "192.168.2.1-255"
	}`)
	json.Unmarshal(jsonstr,&data)
	return method,data
}

func DruleCreate(url string,user string,password string) (interface{},*API) {
	api := LoginAndHandle(url,user,password)
	method,data := DruleCreateData()
	result,err:=api.ZabbixRequest(method,data)
	if err != nil {
		return nil,api
	}
	if result.Error.Code != 0 {
		err = errors.New(result.Error.Message)
		return nil,api
	}
	resultdata := result.Result
	return resultdata,api
}

func DruleDelete(url string,user string,password string) (interface{},*API) {
	api := LoginAndHandle(url,user,password)
	method,data := DruleDeleteData()
	result,err:=api.ZabbixRequest(method,data)
	if err != nil {
		return nil,api
	}
	if result.Error.Code != 0 {
		err = errors.New(result.Error.Message)
		return nil,api
	}
	resultdata := result.Result
	return resultdata,api
}

func DruleGet(url string,user string,password string) (interface{},*API) {
	api := LoginAndHandle(url,user,password)
	method,data := DruleGetData()
	result,err:=api.ZabbixRequest(method,data)
	if err != nil {
		return nil,api
	}
	if result.Error.Code != 0 {
		err = errors.New(result.Error.Message)
		return nil,api
	}
	resultdata := result.Result
	return resultdata,api
}

func DruleUpdate(url string,user string,password string) (interface{},*API) {
	api := LoginAndHandle(url,user,password)
	method,data := DruleUpdateData()
	result,err:=api.ZabbixRequest(method,data)
	if err != nil {
		return nil,api
	}
	if result.Error.Code != 0 {
		err = errors.New(result.Error.Message)
		return nil,api
	}
	resultdata := result.Result
	return resultdata,api
}


